package com.timedomain.him.remake.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AndroidRuntimeException;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.timedomain.him.remake.utils.HLog;
import com.timedomain.him.remake.utils.ShareFileProvider;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class BugreportActivity extends Activity {

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new AlertDialog.Builder(this).setTitle("选择分析类型")
                .setItems(new CharSequence[]{"分析崩溃/闪退","分析可能的问题", "分析输出", "分析全部", "退出"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(which == 0){
                            doAnalyze("-b crash -v raw");
                        }
                        else if(which == 1){
                            doAnalyze("-v raw -s System.err");
                        }
                        else if(which == 2){
                            doAnalyze("-v time -s "+ HLog.TAG);
                        }
                        else if(which == 3){
                            doAnalyze("-v time");
                        }else {
                            finish();
                        }
                    }
                }).setCancelable(false).create().show();
    }

    private void doAnalyze(final String args){
        final ProgressDialog progressDialog = ProgressDialog.show(this,"Bug分析程序","正在分析中，请稍后...",true);
        progressDialog.setCancelable(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> lines = new ArrayList<>();
                StringBuilder logContentBuilder=  new StringBuilder();
                try {
                    Process process = Runtime.getRuntime().exec("logcat -d "+args);
                    try(BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))){
                        String line = null;
                        while ((line = br.readLine())!=null){
                            lines.add(line);
                            logContentBuilder.append(line);
                            logContentBuilder.append("\r\n");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(lines.size() < 1){
                    lines.add("<没有结果或已被清理>");
                }
                logContent = logContentBuilder.toString();
                runOnUiThread(()->showLogs(lines));
                runOnUiThread(progressDialog::dismiss);
            }
        }).start();
    }

    private String logContent = "";

    private void showLogs(List<String> lines){
        ListView lv = new ListView(this);
        lv.setDividerHeight(0);
        lv.setAdapter(new LogAdapter(this,0,lines));
        setContentView(lv);
    }

    class LogAdapter extends ArrayAdapter<String>{

        public LogAdapter(@NonNull @NotNull Context context, int resource, @NonNull @NotNull List<String> objects) {
            super(context, resource, objects);
        }

        @NonNull
        @NotNull
        @Override
        public View getView(int position, @Nullable @org.jetbrains.annotations.Nullable View convertView, @NonNull @NotNull ViewGroup parent) {
            TextView tv = null;
            if(convertView == null){
                convertView = new TextView(getContext());
                tv = (TextView) convertView;
                tv.setTextColor(0xff00ff00);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,8.5f);
            }
            else{

                tv = (TextView) convertView;
            }
            tv.setText(getItem(position));
            return super.getView(position, convertView, parent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("分享Log文件").setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM).setIcon(android.R.drawable.ic_menu_share).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                share();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    public void share(){
        // Creating cache path
        final File cacheLogDir = new File(getCacheDir(),"logs");
        if(!cacheLogDir.exists()){
            cacheLogDir.mkdirs();
        }
        final String filename = System.currentTimeMillis()+".txt";

        final ProgressDialog progressDialog = ProgressDialog.show(this,"Bug分析程序","正在分析中，请稍后...",true);
        progressDialog.setCancelable(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    PrintStream printStream = new PrintStream(new File(cacheLogDir,filename).getPath());
                    printStream.println(logContent);
                    printStream.flush();
                    printStream.close();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent shareIntent = new Intent();
                            shareIntent.setAction(Intent.ACTION_SEND);
                            Uri uri = ShareFileProvider.getUriForFile(BugreportActivity.this,getPackageName(),new File(cacheLogDir,filename));
                            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                            shareIntent.setDataAndType(uri,"text/plain");
                            shareIntent.setClipData(ClipData.newRawUri("", uri));
                            shareIntent.addFlags(
                                    Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            startActivity(Intent.createChooser(shareIntent, "发送日志文件"));
                        }
                    });
                    
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(BugreportActivity.this, "无法分享日志文件，请查看“分析可能的问题”部分", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                runOnUiThread(progressDialog::dismiss);
            }
        }).start();
        


    }
}
